#!/bin/sh
#目录说明：wifi-pay-sdk和WkPay在同一级目录
#使用方法1：./wkpay.sh <WkPay分支名> <commit message>
#使用方法2：sh wkpay.sh <WkPay分支名> <commit message>

if [[ $# = 0 ]]; then
	echo "--->>>err: please input WkPay branch"
	exit 1
fi

#wifi-pay-sdk路径
sdkDir=`pwd`

#WkPay分支名
wkPayBr=$1
#WkPay commit日志
commitMsg=$2

#WkPay目录是否存在
cd ../
if [[ ! -d "WkPay" ]]; then
        git clone git@gitlab.51y5.net:suyong/WkPay.git WkPay
fi

#分支是否存在
cd WkPay
git pull --rebase
git checkout ${wkPayBr}
checkoutStatus=$?
if [[ ! ${checkoutStatus} = 0 ]]; then
	#分支切换失败，新建分支
	git checkout master
	git checkout -b ${wkPayBr}
fi

#返回sdk目录，aar打包
cd ${sdkDir}
git pull --rebase
./gradlew clean WKPR
buildStatus=$?
if [[ ! ${buildStatus} = 0 ]]; then
	exit 1
fi

#获取最新的aar
aarPath=`ls -t SdpOpenWallet/build/AAR/*.aar |head -1`
echo "--->>>new aar path: ${aarPath}"
aarFile=`basename "${aarPath}"`
aarFileWithoutExtension=${aarFile%.*}

wkProject="../WkPay"
wkLibs="${wkProject}/libs"
aarPathOld=`find ${wkLibs} -name '*.aar'`
aarFileOld=`basename "${aarPathOld}"`
aarFileWithoutExtensionOld=${aarFileOld%.*}
echo "--->>>old aar file: ${aarFileWithoutExtensionOld}"

#替换aar
rm -rf ${aarPathOld}
cp ${aarPath} ${wkLibs}

cd ${wkProject}
#修改build.gradle中aar的文件名
OS=`uname`
if [[ ${OS} == "Darwin" ]]; then
	sed -i "" "s/${aarFileWithoutExtensionOld}/${aarFileWithoutExtension}/g" build.gradle
else
	sed -i "s/${aarFileWithoutExtensionOld}/${aarFileWithoutExtension}/g" build.gradle
fi
if [[ ! $? = 0 ]]; then
	exit 1
fi

#检验build.gradle中aar文件名是否替换成功
check=`grep ${aarFileWithoutExtension} build.gradle`
if [[ -z ${check} ]]; then
	exit 1
fi
echo "--->>>new aar file: ${aarFileWithoutExtension}"
echo "--->>>build.gradle: ${check}"

git status
git add .

if [[ -z ${commitMsg} ]]; then
	read -p "Enter commit message: " commitMsg
fi

git commit -m ${commitMsg}
git push origin ${wkPayBr}
